package info.cuatrvientos.org;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class New
 * @author pablo_guerrero
 */
@WebServlet("/New")
public class New extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public New() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.getServletContext().getRequestDispatcher("/new.jsp").forward(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		insertTale(request.getParameter("title"),request.getParameter("tale"));
        this.getServletContext().getRequestDispatcher("/Home").forward(request,response); 
	}
	/**
	 * 
	 * @param title
	 * @param tale
	 */
	 private void insertTale(String title, String tale){
	        
         
         String urlcon = "jdbc:mysql://localhost:3306/onceupon";
         
         Connection conn;
         try {
                 Class.forName("com.mysql.jdbc.Driver");
                 conn = DriverManager.getConnection(urlcon,"root","");
                 
                 String insertSQL= "insert into tale (title , tale) values (?,?)";
                 PreparedStatement prep = conn.prepareStatement(insertSQL);
                 prep.setString(1, title);
                 prep.setString(2, tale);
                 prep.addBatch();
                 prep.executeBatch();
                 
                 
         //      Statement stat = conn.createStatement();
         //      stat.executeUpdate("insert into tale (title , tale) values ('"+title+"','"+tale+"')");          
                 
         } catch (SQLException e) {
                 // TODO Auto-generated catch blockx
                 e.printStackTrace();
         } catch (ClassNotFoundException e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
         }       
 }

}
